package com.xzq.busgstack.client;

import com.xzq.busgstack.util.MsgUtil;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @Author xzq
 * @Description //TODO
 * @Date 2021/11/20 15:21
 * @Version 1.0.0
 **/
public class NettyClient {
    public static void main(String[] args) {
        new NettyClient().connect(9999);
    }

    private void connect(int port) {
        NioEventLoopGroup worker = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap()
                    .group(worker)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.AUTO_READ, true)
                    .handler(new MyChannelInitializer());
            ChannelFuture f = b.connect("127.0.0.1", port).sync();

            f.channel().writeAndFlush(MsgUtil.buildMsg(f.channel().id().toString(), "你好啊,使用ProtoBuf跟你通信，速度快不快？"));
            f.channel().writeAndFlush(MsgUtil.buildMsg(f.channel().id().toString(), "你好啊,使用ProtoBuf跟你通信，速度快不快？"));
            f.channel().writeAndFlush(MsgUtil.buildMsg(f.channel().id().toString(), "你好啊,使用ProtoBuf跟你通信，速度快不快？"));
            f.channel().writeAndFlush(MsgUtil.buildMsg(f.channel().id().toString(), "你好啊,使用ProtoBuf跟你通信，速度快不快？"));
            f.channel().writeAndFlush(MsgUtil.buildMsg(f.channel().id().toString(), "你好啊,使用ProtoBuf跟你通信，速度快不快？"));

            f.channel().closeFuture().sync();

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            worker.shutdownGracefully();
        }
    }
}
